//
//  SelectBirthView.swift
//  选择生日
//
//  Created by 千策万划-mini on 2025/5/3.
//

import Foundation

class SelectBirthView: UIView, UIPickerViewDataSource, UIPickerViewDelegate {

    var blockConfirmClick: (() -> Void)?
    var selectedDate: String = ""

    private var years: [String] = []
    private var months: [String] = []
    private var days: [String] = []

    // MARK: - lazy
    lazy var imageBack: UIImageView = {
        let result = UIImageView()
        result.isUserInteractionEnabled = true
        result.widthHeight = XY(W(355), W(508))
        result.image = UIImage(named: "icon_idcard_example_bg")
        return result
    }()

    lazy var btnClose: UIButton = {
        let result = UIButton()
        result.widthHeight = XY(40 + 16 * 2, 40 + 30 * 2)
        result.tag = 1
        result.addTarget(self, action: #selector(btnClick(_:)), for: .touchUpInside)
        return result
    }()

    lazy var labelTitle: OutlineLabel = {
        let result = OutlineLabel()
        result.resetView(
            title: "Select Date",
            textColor: COLOR_WHITE(),
            font: UIFont.customBoldFont(size: 24),
            shadowColor: UIColor(hex: "#4105A0"),
            outlineColor: UIColor(hex: "#3B0B9A")
        )
        return result
    }()

    lazy var imageContent: UIImageView = {
        let result = UIImageView()
        result.isUserInteractionEnabled = true
        result.widthHeight = XY(W(275), W(290))
        result.image = UIImage(named: "icon_login_input_bg")
        return result
    }()

    lazy var btnConfirm: UIButton = {
        let result = UIButton()
        result.widthHeight = XY(W(168), W(46))
        result.setBackgroundImage(UIImage(named: "icon_pop_cancel"), for: .normal)
        result.tag = 2
        result.addTarget(self, action: #selector(btnClick(_:)), for: .touchUpInside)
        let label = OutlineLabel()
        label.resetView(
            title: "Confirming",
            textColor: COLOR_WHITE(),
            font: UIFont.customBoldFont(size: 16),
            shadowColor: UIColor(hex: "#1B4506"),
            outlineColor: UIColor(hex: "#004600")
        )
        label.centerXCenterY = XY(result.width / 2, result.height / 2)
        result.addSubview(label)
        return result
    }()

    lazy var pickerView: UIPickerView = {
        let result = UIPickerView()
        result.dataSource = self
        result.delegate = self
        return result
    }()

    lazy var imagePickerIndicator: UIImageView = {
        let result = UIImageView()
        result.isUserInteractionEnabled = false
        result.image = UIImage(named: "icon_login_tf_bg")
        return result
    }()

    // MARK: - init
    override init(frame: CGRect) {
        super.init(frame: frame)
        widthHeight = XY(SCREEN_WIDTH, SCREEN_HEIGHT)
        backgroundColor = UIColor(hex: "000000", alpha: 0.8)
        
        loadDateData()
        addSubView()
    }

    @available(*, unavailable)
    required init?(coder _: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func loadDateData() {
        // 获取当前年份
        let currentYear = Calendar.current.component(.year, from: Date())

        // 生成年份数组
        var yearsArray: [String] = []
        for i in 1900 ... currentYear {
            yearsArray.append("\(i)")
        }
        years = yearsArray

        // 生成月份数组
        var monthsArray: [String] = []
        for i in 1 ... 12 {
            monthsArray.append(String(format: "%02d", i))
        }
        months = monthsArray

        // 初始化天数（先设置为2000年1月的天数，后续会根据选择的年月动态调整）
        updateDaysArrayForYear(2000, month: 1)
    }

    func updateDaysArrayForYear(_ year: Int, month: Int) {
        var calendar = Calendar.current
        calendar.timeZone = TimeZone.current

        // 构造日期
        var components = DateComponents()
        components.year = year
        components.month = month
        components.day = 1
        guard let date = calendar.date(from: components) else { return }

        // 获取该月天数
        guard let range = calendar.range(of: .day, in: .month, for: date) else { return }

        // 生成天数数组
        let daysArray = range.map { String(format: "%02d", $0) }
        days = daysArray

        // 刷新 pickerView 的第0列
        pickerView.reloadComponent(0)

        // 如果当前选中的日期超出了新的最大天数，需要调整
        let selectedDay = pickerView.selectedRow(inComponent: 0)
        if selectedDay >= days.count {
            pickerView.selectRow(days.count - 1, inComponent: 0, animated: true)
        }
    }

    // MARK: - 添加
    func addSubView() {
        addSubview(imageBack)
        imageBack.addSubview(labelTitle)
        imageBack.addSubview(imageContent)
        imageBack.addSubview(btnClose)
        imageBack.addSubview(btnConfirm)
        imageContent.addSubview(imagePickerIndicator)
        imageContent.addSubview(pickerView)
        resetView()
    }

    // MARK: - 点击事件
    @objc func btnClick(_ sender: UIControl) {
        feedback()
        sender.addClickAnimate()
        switch sender.tag {
        case 1:
            hide()
        case 2:
            if let block = blockConfirmClick {
                block()
            }
        default:
            break
        }
    }

    // 显示
    func show() {
        if let window = WindowManager.shared.getCurrentWindow() {
            window.endEditing(true)
            // 设置初始状态（比如从底部开始）
            alpha = 0
            imageBack.transform = CGAffineTransform(translationX: 0, y: 50)
            window.addSubview(self)
            // 添加弹出动画
            UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseOut) {
                self.alpha = 1
                self.imageBack.transform = .identity
            }
        }
    }

    // 隐藏
    func hide() {
        // 添加消失动画
        UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseIn) {
            self.alpha = 0
            self.imageBack.transform = CGAffineTransform(translationX: 0, y: 50)
        } completion: { _ in
            self.removeFromSuperview()
            // 重置 transform，以便下次显示
            self.imageBack.transform = .identity
        }
    }

    // MARK: - UIPickerView
    func numberOfComponents(in _: UIPickerView) -> Int {
        return 3
    }

    func pickerView(_: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        switch component {
        case 2:
            return years.count
        case 1:
            return months.count
        case 0:
            return days.count
        default:
            return 0
        }
    }

    func pickerView(_: UIPickerView, rowHeightForComponent _: Int) -> CGFloat {
        return 60
    }

    func pickerView(_: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        let customLabel = (view as? UILabel) ?? {
            let label = UILabel()
            label.textAlignment = .center
            label.font = UIFont.customBoldFont(size: 16)
            label.textColor = UIColor(hex: "#5228D7")
            return label
        }()

        let title: String
        switch component {
        case 0:
            title = days[row]
        case 1:
            title = months[row]
        case 2:
            title = years[row]
        default:
            title = ""
        }

        customLabel.text = title
        customLabel.textColor = UIColor(hex: "#5228D7")
        return customLabel
    }

    func pickerView(_: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        switch component {
        case 2:
            return years[row]
        case 1:
            return months[row]
        case 0:
            return days[row]
        default:
            return nil
        }
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow _: Int, inComponent component: Int) {
        // 当年份或月份改变时，更新天数
        if component == 1 || component == 2 {
            let selectedYear = years[pickerView.selectedRow(inComponent: 2)]
            let selectedMonth = months[pickerView.selectedRow(inComponent: 1)]

            updateDaysArrayForYear(Int(selectedYear) ?? 0,
                                   month: Int(selectedMonth) ?? 0)
        }

        // 更新选中的日期
        let selectedYear = years[pickerView.selectedRow(inComponent: 2)]
        let selectedMonth = months[pickerView.selectedRow(inComponent: 1)]
        let selectedDay = days[pickerView.selectedRow(inComponent: 0)]

        selectedDate = "\(selectedDay)-\(selectedMonth)-\(selectedYear)"
    }

    // MARK: - 重置界面
    func resetView() {
        imageBack.centerXCenterY = XY(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)
        btnClose.rightTop = XY(imageBack.width, 0)
        labelTitle.centerXTop = XY(imageBack.width / 2, W(26))
        imageContent.centerXTop = XY(imageBack.width / 2, W(126))

        pickerView.widthHeight = XY(imageContent.width-W(10)*2, imageContent.height-W(20)*2)
        pickerView.centerXCenterY = XY(imageContent.width / 2, imageContent.height/2)
        for subview in pickerView.subviews {
            subview.backgroundColor = .clear
        }
        
        imagePickerIndicator.widthHeight = XY(imageContent.width - 10 * 2, 60)
        imagePickerIndicator.centerXCenterY = XY(imageContent.width / 2, imageContent.height / 2)

        btnConfirm.centerXTop = XY(imageBack.width / 2, imageContent.bottom + W(15))
    }
    
    // 滚动到指定日期
    func scrollToDate(date: String = "") {
        selectedDate = isStr(date) ? date : "01-01-2000"
        var yearIndex = years.firstIndex(of: "2000") ?? 0
        var monthIndex = months.firstIndex(of: "01") ?? 0
        var dayIndex = days.firstIndex(of: "01") ?? 0

        let dateComponents = selectedDate.split(separator: "-").map { String($0) }
        if dateComponents.count == 3 {
            // 注意顺序：selectedDate 格式为 "dd-MM-yyyy"
            yearIndex = years.firstIndex(of: dateComponents[2]) ?? yearIndex
            monthIndex = months.firstIndex(of: dateComponents[1]) ?? monthIndex
            // 先更新天数数组，确保 days 有正确天数
            updateDaysArrayForYear(Int(dateComponents[2]) ?? 2000, month: Int(dateComponents[1]) ?? 1)
            dayIndex = days.firstIndex(of: dateComponents[0]) ?? dayIndex
        } else {
            // 默认也要保证天数数组正确
            updateDaysArrayForYear(2000, month: 1)
        }
        pickerView.selectRow(dayIndex, inComponent: 0, animated: false)
        pickerView.selectRow(monthIndex, inComponent: 1, animated: false)
        pickerView.selectRow(yearIndex, inComponent: 2, animated: false)
    }
    
}
